package com.hardware.view.service;

import com.hardware.dll.AidierDLL;
import com.hardware.enums.AidierStatus;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ChoiceBox;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 门锁接口配置 实现
 * @作者 韩宗森
 * @创建时间 2024年11月01日 15:26
 */

public class InterfaceSetService {

    /**
     *
     * @param enumClass
     * @return
     * @param <T>
     */
    public <T extends Enum<T>> ObservableList<T> getEnumItems(Class<T> enumClass) {
        return FXCollections.observableArrayList(enumClass.getEnumConstants());
    }

    /**
     * 初始化下拉框
     * @param choiceBox
     * @param enumClass
     * @param <T>
     */
    public <T extends Enum<T>> void initializeChoiceBox(ChoiceBox<T> choiceBox, Class<T> enumClass) {
        ObservableList<T> items = getEnumItems(enumClass);
        choiceBox.setItems(items);
        choiceBox.setValue(items.get(0));
    }

    /**
     * 设置串口
     * @param doorSoftwareKey
     * @param portKey
     * @param encoderKey
     * @param tmEncoderKey
     */
    public void setPort(Integer doorSoftwareKey, Integer portKey, Integer encoderKey, Integer tmEncoderKey) {

        // 定义文件路径
        String filePath = "src/main/resources/application.yml";

        // 读取 YAML 文件
        Yaml yaml = new Yaml();
        try (InputStream in = new FileInputStream(filePath)) {
            // 将 YAML 文件内容转换为 Map
            Map<String, Object> data = yaml.load(in);

            // 修改属性
            Map<String, Object> appData = (Map<String, Object>) data.get("aidier");
            if (appData != null) {
                appData.put("software", doorSoftwareKey);
                appData.put("port", portKey);
                appData.put("encoder", encoderKey);
                appData.put("tmEncoder", tmEncoderKey);
            }

            // 配置 DumperOptions
            DumperOptions options = new DumperOptions();
            options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);

            // 创建新的 Yaml 对象并设置选项
            Yaml newYaml = new Yaml(options);

            // 将修改后的内容写回 YAML 文件
            try (FileWriter writer = new FileWriter(filePath)) {
                newYaml.dump(data, writer);
            }

            System.out.println("application.yml 配置文件更新成功.");
        } catch (IOException e) {
            e.printStackTrace();
        }


        int ret = AidierDLL.INSTANCE.SetPort(doorSoftwareKey, portKey, encoderKey, tmEncoderKey);
        AidierStatus aidierStatus = AidierStatus.fromKey(ret);
        System.out.println("设置串口 SetPort()" + "状态码: " + aidierStatus.getKey() + ", 说明: " + aidierStatus.getValue());

    }
}
